package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ApUserRelationServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/20 21:51
 * @Version 1.0
 */
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Resource
    private ArticleFeign articleFeign;

    @Resource
    private ApUserMapper apUserMapper;

    @Resource
    private ApUserFollowMapper apUserFollowMapper;

    @Resource
    private ApUserFanMapper apUserFanMapper;

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * @param dto app端用户关注操作传递数据封装对象
     * @return 操作结果
     * @Description 关注方法
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1. 校验参数：
        if (dto.getOperation() != 0 && dto.getOperation() != 1) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID, "操作类型有误");
        }
        if (ObjectUtils.isEmpty(dto.getAuthorId())) {
            CustomException.custom(AppHttpCodeEnum.PARAM_REQUIRE, "作者信息不能为空");
        }
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if (ObjectUtils.isEmpty(apAuthor)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注用户不存在");
        }

        //3 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }

        // 关注操作
        if (dto.getOperation() == 0) {

            //4 创建数据（app用户关注和app用户粉丝）
            return followByUserId(user.getId(), apAuthor.getUserId(), dto.getArticleId());
        } else {
            // 取消关注操作
            return followCancelByUserId(user.getId(), apAuthor.getUserId());
        }
    }

    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {
        //1. 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));
        //2. 删除被关注的粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));
        return ResponseResult.okResult();
    }

    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId) {
        //1.获取被关注的作者对应的apUser
        ApUser followUser = apUserMapper.selectById(followUserId);
        if (ObjectUtils.isEmpty(followUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注用户不存在");
        }
        if (userId.intValue() == followUser.getId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需关注自己");
        }

        //2 保存当前用户关注的信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUser.getId())
                .eq(ApUserFollow::getUserId, userId));
        if (!ObjectUtils.isEmpty(apUserFollow)) {
            CustomException.custom(AppHttpCodeEnum.DATA_EXIST, "你已关注该用户");
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short) 1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);

        //3 保存被关注的作者对应的apUser对应的粉丝信息（当前用户）
        //查询粉丝信息
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId).eq(ApUserFan::getUserId, followUserId));
        if (!ObjectUtils.isEmpty(apUserFan)) {
            CustomException.custom(AppHttpCodeEnum.DATA_EXIST, "该粉丝已存在");
        }
        apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short) 0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());
        // 查询粉丝名
        ApUser apUser = apUserMapper.selectById(userId);
        apUserFan.setFansName(apUser.getName());
        apUserFanMapper.insert(apUserFan);
        // 记录关注行为
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setFollowId(followUserId);
        dto.setArticleId(articleId);
        dto.setUserId(apUser.getId());
        //异步发送消息，保存关注行为
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
        return ResponseResult.okResult();
    }
}
